<template>
  <div id="upload">
    <el-upload
      :name='uploadConfig.name'
      :action="uploadConfig.uploadeUrl"
      :multiple="false"
      :accept="uploadConfig.accept"
      :show-file-list='false'
      :http-request='submitUpload'
      :before-upload='handleBeforeUpload'
      :file-list="fileList">
      <el-button size="small" type="primary">图片上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过5M</div>
    </el-upload>
  </div>
</template>
<script>
import browserMD5File from 'browser-md5-file'
import { api, postUploadImg } from 'api/common'
/*
 *  上传成功后父组件通过getImgInfo方法获得服务器图片信息
*/
export default {
  data () {
    return {
      //上传图片用的配置
      uploadConfig: {
        name: 'upload_file',
        //图片上传的链接
        uploadeUrl: api.postUploadImg,
        accept: 'image/png,image/gif,image/jpeg,image/jpg'
      },
      //上传图片列表
      fileList: []
    }
  },
  methods: {
    handleBeforeUpload (file) { //文件上传前
      // console.log('handleBeforeUpload', file)
      const isLt3M = file.size / 1024 / 1024 < 5;
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isLt3M
    },
    submitUpload (obj) {
      let file = obj.file
        // console.warn('submitUpload', file)
      browserMD5File(file, (err, md5) => {
        let fd = new FormData()
        fd.append('upload_file', file)
        fd.append('file_md5', md5)
        this.postUploadImg(fd)
      });
    },
    async postUploadImg (fd) {
      try {
        let back = await postUploadImg(fd)
        back = back.data
        console.log('postUploadImg', back)
        if (back.success) {
          //上传成功后通过getImgInfo方法获得服务器图片信息
          this.$emit('getImgInfo', back)
        } else {
          this.$alert('图片上传失败');
        }
      } catch (err) {
        this.$alert('图片上传失败');
        console.error(err)
      }
    }
  }
}
</script>
<style lang="less" scoped>
  #upload {
    .el-upload__tip{
      display: inline-block;
      margin-left:10px;
    }
  }
</style>

